package com.cyf.plc.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.cyf.library.util.logi
import com.squareup.moshi.Moshi
import dagger.android.support.DaggerFragment
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.EventBusException
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

abstract class BaseFragment<VM : ViewModel, VB : ViewDataBinding> : DaggerFragment() {

    @Inject
    protected lateinit var mViewModelProvider: ViewModelProvider.Factory

    lateinit var mViewModel: VM

    lateinit var mViewBinding: VB

    @Inject
    protected lateinit var moshi: Moshi

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getEventBusException(eventBusException: EventBusException) {
        eventBusException.message?.logi()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mViewBinding = DataBindingUtil.inflate(inflater, layoutId(), container, false)
        mViewBinding.lifecycleOwner = this
        return mViewBinding.root
    }

    abstract fun layoutId(): Int

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = createViewModel()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView()
    }

    abstract fun initView()

    abstract fun createViewModel(): VM

}